// pages/details/details.js
const app = getApp()
var url = require('../../utils/url.js');
var goodsId;
var seckillId;
var priceIndex = 0;
var token;
var user_id = 0;
var formid;
var last_page = 1;
var page = 1
var type;
var end_time;
var shareuSer = 0;
var loadMore = function (that) {
  wx.showLoading({
    title: '加载中',
  });
  if (page == 1) {
    page = 2
  }
  if (page < last_page || page == last_page) {
    console.log(page)
    wx.request({
      url: url.URl + 'goods/evaluation',
      data: { goods_id: goodsId, page: page },
      method: 'get',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res.data)
        wx.hideLoading();
        that.setData({
          evaluate: that.data.evaluate.concat(res.data.data.data)
        });
        page++;
      }
    });
  } else {
    wx.hideLoading();
    that.setData({
      nodata: 1,
      skill: true
    })
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banner: [],
    indicatorDots: true,  //小点
    indicatorColor: "white",
    autoplay: true,  //是否自动轮播
    interval: 3000,  //间隔时间
    duration: 500,  //滑动时间
    tabs: ["商品详情", "视频", "用户评价"],
    activeIndex: 0,
    image: [],
    goods_body: [],
    thisTimeItem: [],
    ads: "",
    goodsprice: "",
    num: 1,
    spec: true,
    specLIst: "",
    totalSpec: "",
    ids: "",
    goodId: "",
    goodsStorage: 0,
    selGoods: [],
    muti_spec: "",
    specId: 0,
    more: true,
    collect: "",
    formid: "",
    goodsInfo: "",
    d: "",
    h: "",
    m: "",
    s: "",
    endDate2: '',
    type:"",
    rulesArray:""
  },   
  onLoad: function (options) {
    var that = this;
    console.log(options)
    wx.getStorage({
      key: 'token',
      success: function (res) {
        token = res.data
      },
    })
    wx.setStorage({
      key: 'rec_id',
      data: options.userId,
    })
    wx.getStorage({
      key: 'userinfo',
      success: function (res) {
        console.log(res.data.id)
        user_id = res.data.id
      }, fail: function () {
        console.log(111)
      }
    })
    console.log(user_id)
    goodsId = options.goodsId;
    type = options.type;
    that.setData({
      type:type
    })
    seckillId = options.id;
    that.getGood()
    that.getEval()
    that.getSpec()
    that.countTime()
  },
  //tab切换
  tabClick: function (e) {
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var activeIndex = that.data.activeIndex;
    if (idx == activeIndex) {
      return false
    } else {
      that.setData({
        activeIndex: idx
      })
    }
  },
  moreL: function () {
    var more = this.data.more;

    this.setData({
      more: !more
    })
  },
  toINDEX: function () {
    wx.navigateTo({
      url: "/pages/seckill/seckill",
    })
  },
  toCART: function () {
    wx.switchTab({
      url: '/pages/cart/cart',
    })
  },
  clickSkuValue:function(e){
    var that=this;
    var checked = e.currentTarget.dataset.check;
    var index=e.currentTarget.dataset.index;
    var specLIst = that.data.specLIst;
    for (var i = 0; i < specLIst.length;i++){
      specLIst[i].checked=false;
      if(i==index){
        specLIst[index].checked = !checked;
      }
    }
    that.setData({
      specLIst: specLIst
    })

    let selGoods = specLIst.filter(function (v) {
      if (v.checked== true) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v;
    });
    console.log(selGoods)
    that.setData({
      selGoods: selGoods
    })
  },
  //获取商品
  getGood() {
    var that = this;
    wx.showLoading({
      title: '加载中..',
    })
    wx.request({
      url: url.URl3 + 'goods/limit/info',
      data: { id: seckillId, user_id: user_id },
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {

        wx.hideLoading()
        var msg = res.data.msg;
        if (res.data.code == 200) {
          console.log(res)
          var row = res.data.data.row;
          var rules = res.data.data.act_info.act_des;
          if (rules){
            var rulesArray = rules.split("|");
            console.log(rulesArray)
            that.setData({
              rulesArray: rulesArray
            })
          }
          
          that.setData({
            ads: res.data.data.ads,
            collect: res.data.data.goods_collect,
            row: row,
            banner: row.goods.goods_images,
            goods_body: row.goods.goods_body,
            goodsprice: row.price,
            goodsYprice: row.goods.goods_price,
            muti_spec: row.goods.muti_spec,
            goods_state: row.goods.goods_state,
            goodsthumb: row.goods.goods_thumb,
            goodsStorage: row.stronge
          })
          end_time = row.end_time.replace(/-/g, '/');
          that.countTime()
        } else if (res.data.code == 201) {

        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },

  //获取评价
  getEval() {
    var that = this;
    wx.showLoading({
      title: '加载中..',
    })
    wx.request({
      url: url.URl + 'goods/evaluation',
      data: { goods_id: goodsId, page: page },
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var msg = res.data.msg;

        wx.hideLoading()
        if (res.data.code == 200) {
          console.log(res)
          last_page = res.data.data.last_page
          that.setData({
            evaluate: res.data.data.data
          })
        } else if (res.data.code == 201) {

        } else {
          // wx.showToast({
          //   title: msg,
          //   icon: 'none',
          //   duration: 2000
          // })
        }
      }
    })
  },
  toCollect: function (e, that, formid) {
    var that = this;
    token = wx.getStorageSync("token")
    formid = e.detail.formId
    this.setData({
      formid: formid
    })
    var collect = this.data.collect;

    if (token) {
      wx.request({
        url: url.URl + 'goods/collect',
        data: { goods_id: goodsId, is_collect: collect },
        method: 'post',
        header: {
          'Authorization': token
        },
        success: function (res) {
          var msg = res.data.msg;
          console.log(res)
          wx.hideLoading()
          if (res.data.code == 200) {
            wx.showToast({
              title: msg,
              icon: 'none',
              duration: 2000,
              success: function () {
                that.setData({
                  collect: !collect
                })
              }
            })

          } else if (res.data.code == 401) {
            wx.showModal({
              title: '提示',
              content: '登录过期，请重新登录',
              showCancel: false,
              confirmText: '我知道了',
              confirmColor: '#DD2626',
              success: function (res) {
                if (res.confirm) {
                  wx.getStorage({
                    key: 'rec_id',
                    success: function (res) {
                      shareuSer = res.data
                      app.onGotUserInfo(e, that, formid, shareuSer)
                    },
                    fail: function () {
                      shareuSer = 0
                      app.onGotUserInfo(e, that, formid, shareuSer)
                    }
                  })
                }
              },
            })
          } else {
            wx.showToast({
              title: msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    } else {
      wx.getStorage({
        key: 'rec_id',
        success: function (res) {
          shareuSer = res.data
          app.onGotUserInfo(e, that, formid, shareuSer)
        },
        fail: function () {
          shareuSer = 0
          app.onGotUserInfo(e, that, formid, shareuSer)
        }
      })
    }
  },
  //倒计时 
  countTime() {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(end_time);//设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差                          
    var d, h, m, s, ms;
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24)+d*24;
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
      ms = Math.floor(leftTime % 1000);
      ms = ms < 100 ? "0" + ms : ms
      s = s < 10 ? "0" + s : s
      m = m < 10 ? "0" + m : m
      h = h < 10 ? "0" + h : h
      // that.setData({
      //   countdown: d + "：" + h + "：" + m + "：" + s + ":" + ms,
      // })
      that.setData({
        d: d,
        h: h,
        m: m,
        s: s
      })
      // console.log(d)
      // console.log(leftTime, 1)    
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 100);
    } else {
      console.log('已截止')
      that.setData({
        countdown: '00:00:00'
      })
    }

  },
  getTime(){
     var that=this;

  },
  //获取规格
  getSpec() {
    var that = this;
    wx.showLoading({
      title: '加载中..',
    })
    wx.request({
      url: url.URl3 + 'goods/limit/spec',
      data: { goods_id: goodsId },
      method: 'post',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var msg = res.data.msg;
        wx.hideLoading()
        if (res.data.code == 200) {
          console.log(res)
          var checked = "checked";
          var specList = res.data.data;
          for (let i = 0; i < specList.length; i++) {
            specList[i][checked] = false;
          }
          that.setData({
            specLIst: specList,
            totalSpec: res.data.data.spec_goods,
          })
        } else if (res.data.code == 201) {

        } else {
          // wx.showToast({
          //   title: msg,
          //   icon: 'none',
          //   duration: 2000
          // })
        }
      }
    })
  },
  bindMinus: function () {
    var num = this.data.num;
    if (num > 1) {
      num--;
    }
    // 将数值与状态写回
    this.setData({
      num: num,
    });
  },
  /* 点击加号 */
  bindPlus: function () {
    var that = this;
    var selGoods = that.data.selGoods;
    var num = this.data.num;
    var goodsStorage = this.data.goodsStorage;
    var limit_num = this.data.limit_num;
    var muti_spec = that.data.muti_spec;
    if (muti_spec == 1 && selGoods.length == 0) {
      wx.showToast({
        title: '请选择规格',
        icon: 'none',
      })
    } else {
      if (num < goodsStorage) {
        num++;
        that.setData({
          num: num,
        });
      } else {
        wx.showToast({
          title: '不能再大了',
          icon: 'none',
        })
      }
    }



    // 将数值与状态写回

  },
  //图片自适应
  imageLoad: function (e) {
    var $width = e.detail.width,    //获取图片真实宽度
        $height = e.detail.height,
        ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 750,           //设置图片显示宽度，左右留有16rpx边距
        viewHeight = 750 / ratio;    //计算的高度值
    var image = this.data.goods_body;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image[e.target.dataset.index] = {
      width: viewWidth,
      height: viewHeight
    }
    // console.log(image)
    this.setData({
      image: image
    })
  },
  tanSpec: function (e, that, formid) {
    var that = this;
    token = wx.getStorageSync("token")
    console.log(e.detail.formId);
    formid = e.detail.formId
    this.setData({
      formid: formid
    })
    if (token) {
      this.setData({
        spec: false
      })
    } else {
      wx.getStorage({
        key: 'rec_id',
        success: function (res) {
          shareuSer = res.data
          app.onGotUserInfo(e, that, formid, shareuSer)
        },
        fail: function () {
          shareuSer = 0
          app.onGotUserInfo(e, that, formid, shareuSer)
        }
      })
    }

  },
  close: function () {
    this.setData({
      spec: true
    })
  },
  //
  /**
   * 生命周期函数--监听页面加载
   */

  tobuy: function () {
    var that = this;
    let selGoods = that.data.selGoods;
    let row = that.data.row.goods;
    var specId = that.data.specId;
    var muti_spec = this.data.muti_spec;

    console.log(token)
    if (muti_spec == 1) {
      if (selGoods.length == 0) {
        wx.showToast({
          title: '请选择规格',
          icon: 'none',
        })
      } else {
        var data = {};
        var dataArray = []
        console.log(selGoods)
        // let DoodsId = "goods_id";
        let spec_goods_id = "spec_goods_id";
        // let goodsNum = "goods_num";
        selGoods[0].goods_name = that.data.row.goods.goods_name;
        selGoods[0].goods_num = that.data.num;
        selGoods[0].spec_goods_id = selGoods[0].id;
        selGoods[0].goods_id = row.id;
        var jsonselGoods = JSON.stringify(selGoods)
        console.log(selGoods)
        wx.navigateTo({
          url: '/pages/ConfirmOrder/ConfirmOrder?goodsInfo=' + jsonselGoods + '&type=3',
        })
      }
    } else {
      var data = {};
      var selGOOds = [];
      var dataArray = []
      console.log(selGoods)
      let goods_id = "goods_id";
      let spec_goods_id = "spec_goods_id";
      let goods_num = "goods_num";
      let price = "price";
      row.goods_num = that.data.num;
      row.spec_goods_id = 0;
      row.goods_id = row.id;
      row.goods_price = that.data.row.price;
      selGOOds.push(row)
      var jsonGoods = JSON.stringify(dataArray)
      var jsonselGoods = JSON.stringify(selGOOds)
      console.log(jsonselGoods)
      wx.navigateTo({
        url: '/pages/ConfirmOrder/ConfirmOrder?goodsInfo=' + jsonselGoods + '&type=3',
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    var row = that.data.row;  
    if (res.from === 'button') {
       
    }
    return {
      title: row.goods.goods_name,
      path: '/pages/seckillXq/seckillXq?goodsId=' + row.goods.id + '&userId=' + user_id + '&type=' + type + '&id=' + row.id,
      imageUrl: row.goods.goods_images[0],
      success: function (res) {
        console.log('成功', res)
      }
    }
  }
})